package everyday;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/6/8 19:07
 * 448. 找到所有数组中消失的数字
 * https://leetcode.cn/problems/find-all-numbers-disappeared-in-an-array/
 */
public class Solution448 {

    // 原地哈希
    public List<Integer> findDisappearedNumbers(int[] nums) {
        // 4 3 2 7 8 2 3 1
        // 原地哈希, 0 1 2 索引依次对应 1 2 3
        int index = 0;
        int n = nums.length;
        while (index < n) {
            if (nums[index] == index + 1) {
                ++index;
                continue;
            }
            int tempIndex = nums[index] - 1;
            if (nums[tempIndex] == nums[index]) {
                ++index;
                continue;
            }
            int temp = nums[tempIndex];
            nums[tempIndex] = nums[index];
            nums[index] = temp;
        }
        System.out.println(Arrays.toString(nums));
        // 一次遍历找到缺少的数字
        List<Integer> ret = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            if (nums[i] != i + 1) {
                ret.add(i + 1);
            }
        }
        return ret;
    }

    public static void main(String[] args) {
        new Solution448().findDisappearedNumbers(new int[]{4, 3, 2, 7, 8, 2, 3, 1});
    }
}
